#-*- coding:utf8 -*-
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* limit
* channels
* url
* showas
"""

import re, time
from core.ircfuncs import *
from core.ircfuncs import _levels
from util.functions import join_list, status
from core.optimizers import _path

def channels(bot, evt, cmd):
	""".channels [-chan <channel>] -lang ca -fam wikipedia -listen -!log -reply -!report -clr -lnk -join [-trg #tag]"""
	qchan = cmd.opts['chan'] or cmd.arguments or evt.target
	print qchan
	if qchan and cmd.action == 'props':
		if qchan in bot.channels_extended.keys():
			chan_props = bot.channels_extended[qchan]
			bot.reply(evt,
				"%(ch)s &B;-lang&N; %(ln)s &B;-fam&N; %(fm)s &B;-listen&N; %(ls)s "
				" &B;-log&N; %(lg)s &B;-reply&N; %(rl)s &B;-report&N; %(rt)s"
				"&B;-trg&N; %(tr)s &B;-clr&N; %(cl)s &B;-lnk&N; %(lk)s &B;-join&N; %(jn)s",
				ch = qchan,
				ln = chan_props['lang'],
				fm = chan_props['fam'],
				ls = chan_props['listen'],
				lg = chan_props['log'],
				rl = chan_props['reply'],
				rt = chan_props['report'],
				tr = chan_props['triggers'].replace("\\",""),
				cl = chan_props['colors'],
				lk = chan_props['links'],
				jn = chan_props['join'],
			)
		else:
			bot.reply(evt, "No such channel.")
		return

	if not has_access(bot, channels.level, evt): return
	#if not access_is(bot, ("admin","owner")): return
	if cmd.action in ("modify", "change", "edit"):
		if bot.channels_extended.has_key(qchan):
			reveal = ""
			for key in cmd.opts.keys():
				if bot.channels_extended[qchan].has_key(key):
					if qchan == bot.defchan and key in ("listen", "lst", "reply", "rpl"):
						#default channel can not be switched off
						if not cmd.opts[key]: cmd.opts[key] = True
					if key not in ("triggers", "trg"):
						bot.channels_extended[qchan][key] = cmd.opts[key]
					if key == "lang": bot.channels[qchan].lang = cmd.opts[key]
					elif key == "fam": bot.channels[qchan].fam = cmd.opts[key]
					elif key in ("listen", "lst"): bot.channels[qchan].listen = cmd.opts[key]
					elif key == "log": bot.channels[qchan].log = cmd.opts[key]
					elif key == ("reply", "rpl"): bot.channels[qchan].reply = cmd.opts[key]
					elif key == ("report", "rpt"):
						bot.channels[qchan].report = cmd.opts[key]
						reveal = (qchan, bot.channels[qchan].report)
					elif key in ("color", "clr"): bot.channels[qchan].colors = cmd.opts[key]
					elif key in ("links", "lnk"): bot.channels[qchan].links = cmd.opts[key]
					elif key == "join": bot.channels[qchan].join = cmd.opts[key]
			if  cmd.opts.has_key("trg") or cmd.opts.has_key("triggers"):
				bot.reply(evt, "Command .channels can't modify triggers. Try .triggers command instead.")
			bot.channels_extended.save()
			chan_props = bot.channels_extended[qchan]
			bot.reply(
				evt,
				"%(ch)s &B;lang&N;:&N; %(ln)s, &B;fam&N;: %(fm)s, &B;listen&N;: %(ls)s, "
				"&B;log&N;: %(lg)s, &B;reply&N;: %(rl)s, &B;report&N;: %(rt)s, "
				"&B;triggers&N;: %(tr)s, &B;colors&N;: %(cl)s, "
				"&B;links&N;: %(lk)s &B;join:&N; %(jn)s",
				ch = qchan,
				ln = chan_props['lang'],
				fm = chan_props['fam'],
				ls = chan_props['listen'],
				lg = chan_props['log'],
				rl = chan_props['reply'],
				rt = chan_props['report'],
				tr = chan_props['triggers'].replace("\\",""),
				cl = chan_props['colors'],
				lk = chan_props['links'],
				jn = chan_props['join']
			)
			if reveal:
				#send a msg about report status to referred channel
				bot.privmsg(reveal[0], "%s reporting switched %s" % (chan, status(reveal[1])))
		else:
			bot.reply(evt, "no such channel")
		return
	elif cmd.action in ("create", "new", "add"):
		if qchan not in bot.channels_extended.keys():
			bot.channels_extended.update(
				qchan, {
						'lang': cmd.opts['lang'],
						'fam': cmd.opts['fam'],
						'listen': cmd.opts['listen'] or cmd.opts['lst'],
						'log': cmd.opts['log'],
						'reply': cmd.opts['reply'] or cmd.opts['rpl'],
						'report': cmd.opts['report'] or cmd.opts['rpt'],
						'triggers': bot.triggers,
						'colors': cmd.opts['colors'] or  cmd.opts['clr'],
						'links': cmd.opts['links'] or  cmd.opts['lnk'],
						'join': cmd.opts['join'],
					}
			)
			bot.channels_extended.save()
			if bot.channels.has_key(qchan):
				bot.channels[qchan].lang = cmd.opts['lang']
				bot.channels[qchan].fam = cmd.opts['fam']
				bot.channels[qchan].listen = cmd.opts['listen'] or cmd.opts['lst']
				bot.channels[qchan].log = cmd.opts['log']
				bot.channels[qchan].reply = cmd.opts['reply'] or cmd.opts['rpl']
				bot.channels[qchan].report = cmd.opts['report'] or cmd.opts['rpt']
				bot.channels[qchan].triggers = bot.triggers
				bot.channels[qchan].colors = cmd.opts['colors'] or cmd.opts['clr']
				bot.channels[qchan].links = cmd.opts['links'] or cmd.opts['lnk']
				bot.channels[qchan].join = cmd.opts['join']
			bot.reply(evt, "Channel was added successfully.")
			return
	elif cmd.action in ("remove", "del") and qchan:
		if bot.channels_extended.has_key(qchan):
			bot.channels_extended.delete(qchan)
			bot.reply(evt, "Channel: %s deleted.", qchan)
		else:
			bot.reply(evt, "No such channel")
	elif cmd.action in ("info", "all"):
		for chan in bot.channels:
			bot.reply(
				evt,
				"%(ch)s &B;-lang&N; %(ln)s &B;-fam&N; %(fm)s &B;-listen&N; %(ls)s "
				" &B;-log&N; %(lg)s &B;-reply&N; %(rl)s &B;-report&N; %(rt)s"
				"&B;-trg&N; %(tr)s &B;-clr&N; %(cl)s &B;-lnk&N; %(lk)s &B;-join&N; %(jn)s",
				ch = chan,
				ln = bot.channels[chan].lang,
				fm = bot.channels[chan].fam,
				ls = bot.channels[chan].listen,
				lg = bot.channels[chan].log,
				rl = bot.channels[chan].reply,
				rt = bot.channels[chan].report,
				tr = bot.channels[chan].triggers.replace("\\",""),
				cl = bot.channels[chan].colors,
				lk = bot.channels[chan].links,
				jn = bot.channels[chan].join,
			)
channels.rule = "channels"
channels.level = "support"

def properties(bot, evt, cmd):
	"""Same command of ".channels <channel> :props"""
	if not has_access(bot, properties.level, evt): return
	chan = cmd.arguments
	if chan in bot.channels_extended.keys():
		chan_props = bot.channels_extended[chan]
		bot.reply(
			evt,
			"%(ch)s &B;-lang&N; %(ln)s &B;-fam&N; %(fm)s &B;-reply&N; %(rl)s "
			"&B;-listen&N; %(ls)s &B;-report&N; %(rt)s &B;-log&N; %(lg)s "
			"&B;-trg&N; %(tr)s &B;-clr&N; %(cl)s &B;-lnk&N; %(lk)s &B;-join&N; %(jn)s",
			ch = chan,
			ln = chan_props['lang'],
			fm = chan_props['fam'],
			ls = chan_props['listen'],
			rl = chan_props['reply'],
			rt = chan_props['report'],
			lg = chan_props['log'],
			tr = chan_props['triggers'].replace("\\",""),
			cl = chan_props['colors'],
			lk = chan_props['links'],
			jn = chan_props['join'],
		)
	else:
		bot.reply(evt, "No such channel.")
properties.rule = "props"
properties.level = "support"

def triggers_(bot, evt, cmd):
	""".triggers [-ch <chan>] [-a <chr>] [-r <chr>] [-reset] — &l;handle triggers on a channel.&N; &e;-a:&N; append, &e;-r:&N; remove, &e;-reset:&N; restore default values, &e;<chr>&N; one character of user's choice."""
	chan = cmd.dict['chan'] or evt.chan
	print chan, cmd.dict['chan'], cmd.dict['key1'], cmd.dict['val1'], cmd.dict['key2'], cmd.dict['val2'], cmd.dict['rst']

	if cmd.dict['key1'] and cmd.dict['key1'] in "ar": cmd.opts[cmd.dict['key1']] = cmd.dict['val1']
	if cmd.dict['key2'] and cmd.dict['key2'] in "ar": cmd.opts[cmd.dict['key2']] = cmd.dict['val2']
	if cmd.dict['rst']: cmd.opts['reset']=True
	if not bot.channels_extended.has_key(chan):
		bot.reply(evt, "No such channel.")
		return True
	if cmd.opts['a']:
		triggers = list(bot.channels_extended[chan]['triggers'].replace("\\",""))
		for x in cmd.opts['a']:
			if not x in triggers: triggers.append(x)
		bot.reply(evt, "%s &B;triggers:&N; %s", chan, " ".join(triggers))
		triggers = "%s" % escape_for_regexp("".join(triggers))
		if bot.channels.has_key(chan): bot.channels[chan].triggers  = triggers
		bot.channels_extended[chan]['triggers'] = triggers
		bot.channels_extended.save()
	elif cmd.opts['r']:
		triggers = list(bot.channels_extended[chan]['triggers'].replace("\\",""))
		if len(triggers)<=1:
			bot.reply(evt, "Can't remove more triggers")
			return True
		elif len(triggers)>1:
			for x in cmd.opts['r']:
				if x in triggers: triggers.remove(x)
			bot.reply(evt, "%s &B;triggers:&N; %s", chan, " ".join(triggers))
			triggers = escape_for_regexp("".join(triggers))
			if bot.channels.has_key(chan): bot.channels[chan].triggers  = triggers
			bot.channels_extended[chan]['triggers'] = triggers
			bot.channels_extended.save()
	elif cmd.opts['reset']:
		bot.channels[chan].triggers = \
		bot.channels_extended[chan]['triggers'] = bot.triggers
		bot.channels_extended.save()
		bot.reply(evt, "%s &B;triggers:&N; %s", chan, " ".join([x for x in bot.triggers.replace("\\","")]))
	else:
		bot.reply(evt, "%s &B;triggers:&N; %s", chan, " ".join([x.replace("\\","") for x in bot.channels_extended[chan]['triggers']]))
triggers_.rule = re.compile(r"(?:$both)trig(?:gers)?(?: (?:-ch )?(?P<chan>#[^ ]+)?(?:(?: -(?P<key1>[ra]) (?P<val1>[!@$%&,;:.\-_><]+))(?: -(?P<key2>[ra]) (?P<val2>[!@$%&,;:.\-_><]+))?)?(?P<rst>-reset)?)?")
triggers_.fullmsg = True
triggers_.level = "tester"

def show_triggers_(bot, evt, cmd):
	if not_on_channel(bot, bot.defchan): return True
	for chan in bot.channels:
		bot.reply(evt, "%s &B;triggers&N;: %s", chan, bot.channels[chan].triggers.replace("\\",""))
		time.sleep(1)
show_triggers_.rule = "t"
show_triggers_.level = "tester"

def switch_listen(bot, evt, cmd):
	if not has_access(bot, switch_listen.level, evt): return
	chan = cmd.arguments if cmd.arguments in bot.channels.keys() else evt.target if evt.target != bot.defchan else ""
	if not chan:
		bot.reply(evt, "No such channel. Unknown channel: %s", cmd.arguments)
		return True
	listen = bot.channels[chan].listen
	switch = not listen
	if chan == bot.defchan and switch == False: return True
	bot.channels[chan].listen = switch
	bot.channels_extended[chan]['listen'] = switch
	bot.channels_extended.save()
	bot.reply(evt, "%s listening switched %s", chan, status(switch))
switch_listen.rule = "listen"
switch_listen.level = "support"

def switch_reply(bot, evt, cmd):
	if not has_access(bot, switch_reply.level, evt): return
	chan = cmd.arguments if cmd.arguments in bot.channels.keys() else evt.target
	reply = bot.channels[chan].reply
	switch = not reply
	if chan == bot.defchan and switch == False: return True
	bot.channels[chan].reply = switch
	bot.channels_extended[chan]['reply'] = switch
	bot.channels_extended.save()
	bot.reply(evt, "%s replying switched %s", chan, status(switch))
switch_reply.rule = "reply"
switch_reply.level = "support"

def switch_report(bot, evt, cmd):
	#user only pretends to know the report status
	if cmd.opts['s'] or cmd.opts['status']:
		if cmd.arguments and cmd.arguments in bot.channels.keys():
			bot.reply(evt, "%s reporting status is %s", cmd.arguments, status(bot.channels[cmd.arguments].report))
		elif cmd.arguments and cmd.arguments not in bot.channels.keys():
			bot.reply(evt, "No such channel. Unknown channel %s", cmd.arguments)
		else:
			bot.reply(evt, "%s reporting status is %s", evt.chan, status(bot.channels[evt.chan].report))
		return True
	#user omitted -status key but, he/she doesn't has appropiate level, then we'll give the status
	if _levels.index(evt.level) <= _levels.index("trusty") and (not cmd.arguments or cmd.arguments == evt.chan):
		bot.reply(evt, "%s reporting status is %s", evt.chan, status(bot.channels[evt.chan].report))
		return True
	#user has rights, and we supposed he know what he can do.
	#if channel is unknown, channel will be the default channel.
	#default channel can not be modified
	chan = cmd.arguments if cmd.arguments in bot.channels.keys() else evt.target
	if not has_access(bot, switch_report.level, evt): return
	report = bot.channels[chan].report
	switch = not report
	if chan == bot.defchan and switch == True: return True
	bot.channels[chan].report = switch
	bot.channels_extended[chan]['report'] = switch
	bot.channels_extended.save()
	bot.reply(evt, "%s reporting switched %s", chan, status(switch))
	if evt.chan != chan:
		#send a msg about report status to referred channel
		bot.privmsg(chan, "%s reporting switched %s" % (chan, status(switch)))
switch_report.rule = "report"
switch_report.level = "support"

def switch_log(bot, evt, cmd):
	if not has_access(bot, switch_log.level, evt): return
	chan = cmd.arguments if cmd.arguments in bot.channels.keys() else evt.target
	log = bot.channels[chan].log
	switch = not log
	if chan == bot.defchan and switch == True: return True
	bot.channels[chan].log = switch
	bot.channels_extended[chan]['log'] = switch
	bot.channels_extended.save()
	bot.reply(evt, "%s logging switched %s", chan, status(switch))
switch_log.rule = "log"
switch_log.load = False
switch_log.level = "support"

def switch_links(bot, evt, cmd):
	if not has_access(bot, switch_links.level, evt): return
	chan = cmd.arguments if cmd.arguments in bot.channels.keys() else evt.target
	links = bot.channels[chan].links
	if cmd.opts["s"] or cmd.opts["stat"]:
		bot.reply(evt, "%s links switched %s", chan, status(links))
		return True
	switch = not links
	if chan == bot.defchan and switch == False:
		return True
	bot.channels[chan].links = bot.channels_extended[chan]['links'] = switch
	bot.channels_extended.save()
	bot.reply(evt, "%s links switched %s", chan, status(switch))
switch_links.rule = "links"
switch_links.level = "support"

def def_lang(bot, evt, cmd):
	if not has_access(bot, switch_links.level, evt): return
	chan=None
	items = cmd.arguments.split(" ")
	for item in items:
		if item.startswith("#"): chan = item
		else: new_lang = item
	if not chan: chan = evt.chan

	if chan not in bot.channels.keys():
		bot.reply(evt, "No such channel.")
		return True
	if chan not in bot.channels_extended.keys():
		bot.reply(evt, "No such channel.")
		return True

	if not "%s.py" % new_lang in _path.files("lang"):
		#print ", ".join([f for f in _path.files("lang") if f.endswith(".py")])
		bot.reply(evt, "file lang/%s.py not found" % new_lang)
		return True
	elif bot.channels[chan].lang != new_lang:
		bot.channels[chan].lang = new_lang
		bot.channels_extended[chan]['lang'] = new_lang
		bot.channels_extended.save()
		bot.reply(evt, "%s lang changed to %s", chan, new_lang)
	else:
		bot.reply(evt, "channel %s has already language %s defined", chan, new_lang)
def_lang.rule = "lang"
def_lang.level = "support"

def accounts(bot, evt, cmd):
	""".acc [-u ]<user> -l[ang] <code> [-L|-level] {user|support|admin} -w[ikiuser] <Wikiaccount> -f[am] <Wikisite> -a[liases]"""
	#account = cmd.opts['user'] or cmd.opts['u'] or cmd.arguments or evt.source
	account = get_user(cmd, evt)
	acc=get_account(bot, account)
	if cmd.action in ('props',"read"):
		if bot.accounts.has_key(account):
			acc = bot.accounts[account].copy()
			acc.update({"wiki": quiet_nick(acc['wiki'], bot.channels[evt.chan].users())})
			acc.update({"aliases": join_list([quiet_nick(nick, bot.channels[evt.chan].users()) for nick in acc['aliases']], evt.lang)})
			bot.reply(evt,
				"&B;lang:&N; %(lang)s &B;family:&N; %(fam)s &B;wikiuser:&N; %(wiki)s &B;level:&N; %(level)s &B;aliases:&N; %(aliases)s" % acc
			)
		else:
			bot.reply(evt, "No such account.")
		return
	elif cmd.action == 'all':
		for acc in bot.accounts():
			users = bot.channels[evt.chan].users()
			bot.reply(evt,
						"&B;acc:&N; %(a)s &B;lang:&N; %(l)s &B;family:&N; %(f)s &B;wikiuser:&N; %(w)s &B;level:&N; %(L)s &B;aliases:&N; %(A)s",
				a = quiet_nick(acc, users),
				l = bot.accounts[acc]['lang'],
				f = bot.accounts[acc]['fam'],
				w = quiet_nick(bot.accounts[acc]['wiki'], users),
				L = bot.accounts[acc]['level'],
				A = join_list([quiet_nick(nick, users) for nick in bot.accounts[acc]['aliases']], evt.lang)
			)
		return True

	if not has_access(bot, accounts.level, evt): return
	defined = {}
	for key in cmd.opts.keys():
		if key in ("lang", "l"):
			defined["lang"]= cmd.opts[key]
		elif key in ("fam", "f"):
			defined["fam"] = cmd.opts[key]
		elif key in ("level", "L"):
			defined["level"] = cmd.opts[key]
		elif key in ("wiki", "wikiuser", "w"):
			defined['wiki'] = cmd.opts[key]
		elif key in ("alias", "aliases", "a"):
			if isinstance(cmd.opts[key], basestring):
				cmd.opts[key] = [cmd.opts[key]]
			defined['aliases'] = cmd.opts[key] or []

	#if not defined.has_key('aliases'): defined['aliases']=[]
	if defined.has_key('aliases') and defined['aliases']==None: defined['aliases']=[]

	if defined.has_key('level') and defined['level'] not in _levels:
		defined.update({'level':_levels[0]})
		bot.reply(evt, "Unknown level. Level was replaced by 'user'.")

	if cmd.action == "rename":
		if bot.accounts.get(account) and cmd.opts['new']:
			if _levels.index(evt.level) < _levels.index(bot.accounts[account]['level']):
				bot.reply(evt, "you don't have enough permissions.")
				return True
			bot.accounts.update(cmd.opts['new'], bot.accounts[account])
			bot.accounts.delete(account)
			bot.accounts.save()
			bot.reply(evt, "Account %s was renamed as %s.", account, cmd.opts['new'])
		else:
			bot.reply(evt, "No such account.")
		return
	elif cmd.action in ("modify", "change", "edit"):
		newdef=0
		if bot.accounts.get(account):
			if _levels.index(evt.level) < _levels.index(bot.accounts[account]['level']):
				bot.reply(evt, "you don't have enough permissions.")
				return True
			for key in defined:
				if bot.accounts[account].has_key(key):
					if key == "level" and defined[key] not in _levels:
						bot.reply(evt, "Unknown level.")
						continue
					if bot.accounts[account][key] != defined[key]:
						if key == "aliases":
							if isinstance(defined[key], basestring):
								if defined[key].startswith("+ "):
									defined[key] = [irc_lower(defined[key][2:])]
									if isinstance(bot.accounts[account][key], basestring):
										bot.accounts[account][key] = [bot.accounts[account][key]]
									bot.accounts[account][key] += defined[key]
								elif defined[key].startswith("- "):
									bot.accounts[account][key].remove(defined[key][2:])
								else:
									bot.accounts[account][key] += [defined[key]]
							else:
								if not bot.accounts[account][key]:
									bot.accounts[account][key] = []
								elif isinstance(bot.accounts[account][key], basestring):
									bot.accounts[account][key] = [bot.accounts[account][key]]
								if defined[key][0].startswith("+ "):
									defined[key][0] = defined[key][0][2:]
									action = "+"
								elif defined[key][0].startswith("- "):
									defined[key][0] = defined[key][0][2:]
									action = "-"
								else:
									action="+"
								if action == "+":
									for alias in defined[key]:
										bot.accounts[account][key].append(alias)
								else:
									for alias in defined[key]:
										if alias in bot.accounts[account][key]:
											bot.accounts[account][key].remove(alias)
						else:
							bot.accounts[account][key] = defined[key]
						newdef+=1
					elif bot.accounts[account][key] == defined[key]:
						bot.reply(evt, "key %s is already defined as %s", key, defined[key])
			if newdef>0:
				bot.accounts.save()
				copy = bot.accounts[account].copy()
				users = bot.channels[evt.chan].users()
				copy.update({"wiki": quiet_nick(bot.accounts[account]['wiki'], users)})
				copy.update({"aliases": join_list([quiet_nick(nick, users) for nick in bot.accounts[account]['aliases']], evt.lang)})
				bot.reply(evt, "&B;lang:&N; %(lang)s, &B;fam:&N; %(fam)s, &B;level:&N; %(level)s, &B;wikiuser:&N; %(wiki)s &B;aliases:&N; %(aliases)s" % copy)
			else:
				bot.reply(evt, "no key was updated.")
		else:
			bot.reply(evt, "No such account.")
		return
	elif cmd.action in ("del", "remove"):
		if _levels.index(evt.level) < _levels.index(bot.accounts[account]['level']):
			bot.reply(evt, "you don't have enough permissions.")
			return True
		bot.accounts.delete(account)
		bot.accounts.save()
		bot.reply(evt, "Account removed.")
		return
	elif cmd.action in ("create", "new", "add"):
		if defined.has_key('lang') and defined.has_key('fam') \
		and defined.has_key('level') and defined.has_key('wiki') and defined.has_key('aliases'):
			bot.accounts.update(
			account, {
				'lang': defined['lang'], #like "ca"
				'level': defined['level'], #can be one of ("admin", "support", "trusty", "user")
				'wiki': defined['wiki'], #nick in Wikimedia projects
				'fam': defined['fam'], #home wiki family project, like "wikipedia"
				'aliases': defined['aliases'] #home wiki family project, like "wikipedia"
				}
			)
			bot.accounts.save()
			bot.reply(evt, "Account created successfully.")
		else:
			keys=("lang", "fam", "wiki", "aliases", "level")
			missing = [key for key in keys if key not in defined]
			if missing:
				bot.reply(evt, "&B;missing parameters:&N; %s", ", ".join(missing))
		return
	elif not cmd.action:
		bot.reply(evt, "Some action is required.")
	else:
		bot.reply(evt, "something is not cool for user %s" % account)
		return
accounts.rule = "acc"
accounts.level = "support"

def freenodeaccount(bot, evt, cmd):
	"""".fracc <user>" returns the freenode account related to nickname."""
	if not has_access(bot, freenodeaccount.level, evt): return
	nick = cmd.arguments or evt.source
	nick = bot.nicks.get(nick, '')
	if nick:
		bot.reply(evt, nick)
	else:
		bot.reply(evt, "No such nick.")
freenodeaccount.rule = "fracc"
freenodeaccount.level = "support"

def freenodecheck(bot, evt, cmd):
	"""".fracc <user>" returns the freenode account related to nickname."""
	nick = cmd.arguments or evt.source
	bot.whois(nick)
freenodecheck.rule = "check"
freenodecheck.level = "support"

def chanlist(bot, evt, cmd):
	""".chanlist [<channel>]"""
	if not "@wm" in cmd.arguments:
		chlist = bot.channels.keys()
		bot.reply(evt, join_list(chlist, evt.lang))
	elif "@wm" in cmd.arguments:
		chlist = bot.bots(("slave", 1)).channels.keys()
		bot.reply(evt, join_list(chlist, evt.lang))
chanlist.rule = "chanlist"
